import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  FlatList,
  RefreshControl,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {TextButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {queryAuctionList} from '../../api/auction';
import AuctionCell from '../home/components/AuctionCell';
import ChainUtils from '../../utils/chain/ChainUtils';
import BigNumber from 'bignumber.js';
import {formatMinuteTime, formatLeftTime} from '../../utils/tools';

//#FFCB26
class MyAuctions extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      isRefreshing: false,
      auctions: [],
      auctionListPage: 1,
      auctionListTotal: 0,
      auctionListSize: 10,
      auctionListIsLoadMore: false,
    };
  }

  async componentDidMount() {
    super.componentDidMount();

    this.setState({
      isRefreshing: true,
    });
    await this._initData();
    this.setState({
      isRefreshing: false,
    });
  }

  _initData = async () => {
    let userToken = this.props.userInfo.token;

    let queryAddress = this.props.navigation.state?.params?.address;

    let {auctionListPage, auctionListSize} = this.state;
    await queryAuctionList({
      page: auctionListPage,
      size: auctionListSize,
      userToken,
      address: queryAddress
        ? queryAddress
        : this.props.userInfo.metamaskAddress,
    })
      .then((res) => {
        let newActions = res.data.rows.map((item) => {
          console.log(item.expireDate);

          let timeSpace =
            new Date(item.expireDate * 1000) - new Date().valueOf();

          let startPrice = new BigNumber(item.startPrice);
          const decimal = new BigNumber(Math.pow(10, item.payCoinDecimal));
          let vAmount = parseFloat(startPrice.dividedBy(decimal));
          startPrice = ChainUtils.subStringNum(vAmount, 4);

          let bidValue = new BigNumber(item.bidValue);
          let bAmount = parseFloat(bidValue.dividedBy(decimal));
          bidValue = ChainUtils.subStringNum(bAmount, 4);

          let dealPrice = new BigNumber(item.dealPrice);
          let dAmount = parseFloat(dealPrice.dividedBy(decimal));
          dealPrice = ChainUtils.subStringNum(dAmount, 4);

          return {
            ...item,
            img: item.img,
            leftTime: formatLeftTime(timeSpace),
            startPrice,
            bidValue,
            dealPrice,
          };
        });

        if (auctionListPage != 1) {
          newActions = this.state.auctions.concat(newActions);
        }

        this.setState({
          auctions: newActions,
          auctionListTotal: res.data.pageInfo.total,
          auctionListIsLoadMore: false,
        });
      })
      .catch((err) => {
        console.log('查询拍卖列表出错' + err);
      });
  };

  _renderAuctionCellItem = (item) => (
    <AuctionCell
      auction={item.item}
      swapSymbol={this.props.swapSymbol}
      onPressItem={() => this._onPressAuction(item.item)}
    />
  );

  _onPressAuction = async (item) => {
    console.log('点击拍卖详情');
    //
    let queryAddress = this.props.navigation.state?.params?.address;
    if (queryAddress) {
      this.props.navigation.state.params.refreshAuction(item);
      this.props.navigation.goBack();
    } else {
      this.props.navigation.navigate('Auction', {auction: item});
    }
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        {I18n.t('common.no_data')}
      </Text>
    </View>
  );
  _renderItemSeparatorComponent = () => (
    <View style={{height: 10, backgroundColor: 'transparent'}} />
  );

  auctionListFooterComponent = () => {
    console.log(this.state);
    console.log(this.state.auctions.length);
    let showLoadingMore =
      this.state.auctionListTotal >=
      this.state.auctionListPage * this.state.auctionListSize;
    return this.state.auctions.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : ''}
          </Text>
        </View>
      </View>
    );
  };

  onAuctionFlatlistEndReached() {
    console.log('>>上拉加载>>>');
    const {
      auctionListPage,
      auctionListIsLoadMore,
      auctionListTotal,
      auctions,
    } = this.state;

    if (auctions.length < auctionListTotal && !auctionListIsLoadMore) {
      this.setState(
        {
          auctionListPage: auctionListPage + 1,
          auctionListIsLoadMore: true,
        },
        () => {
          this._initData();
        },
      );
    }
  }

  renderComponent = () => {
    // let queryAddress = this.props.navigation.state.params.address;

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Auctions"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();

              //如果有Home则返回Home
              let stack = this.props.navigationStack;
              console.log(stack);
              if (stack && stack.some((item) => item.routeName == 'UserInfo')) {
                this.props.navigation.goBack();
              } else if (
                stack &&
                stack.some((item) => item.routeName == 'Home')
              ) {
                let roomIdx = stack.length;
                stack.map((item, idx) => {
                  console.log(item);
                  if (idx == roomIdx + 1) {
                    console.log('返回room页面');
                    this.props.navigation.goBack(item.key);
                  } else if (item.routeName == 'Home') {
                    roomIdx = idx;
                  }
                });
              } else {
                this.props.navigation.goBack();
              }
            },
          }}
        />
        <View style={{flex: 1}}>
          <FlatList
            style={{flex: 1, marginTop: 10}}
            data={this.state.auctions}
            keyExtractor={(item, index) => item.auctionId} // 给定的item生成一个不重复的key
            renderItem={this._renderAuctionCellItem}
            ListEmptyComponent={this._renderEmptyView}
            ItemSeparatorComponent={this._renderItemSeparatorComponent}
            ListFooterComponent={this.auctionListFooterComponent}
            onEndReached={() => this.onAuctionFlatlistEndReached()}
            onEndReachedThreshold={0.2}
            contentContainerStyle={{flexGrow: 1}}
            ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
            refreshControl={
              <RefreshControl
                tintColor="white"
                refreshing={this.state.isRefreshing}
                onRefresh={this.auctionListOnRefresh}
                colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                progressBackgroundColor="#ffffff"
              />
            }
          />
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </View>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  navigationStack: state.Layout.navigationStack,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(MyAuctions);
